<template>
  <el-card v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.1)" class="board-hover">
    <div slot="header">
      <span>APP许可信息</span>
      <el-button style="float: right; padding: 3px 0" type="text" icon="el-icon-refresh-right" @click="getlist()"> </el-button>
      <span class="tip">每小时自动刷新:{{loadTime}}</span>
    </div>
    <div class="board">
      <el-row :gutter="12">
        <el-col :span="24">
          <el-button class="board-button" type="primary" round icon="el-icon-download" @click="downloadFile">
            许可申请下载
          </el-button>
          <el-button class="board-button" type="primary" round icon="el-icon-upload2" @click="importFile">
            许可文件上传
          </el-button>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="4">
          <div class="board-title">授权日期</div>
          <div class="board-text">{{ license.startDate }}</div>
        </el-col>
        <el-col :span="4">
          <div class="board-title">授权到日期</div>
          <div class="board-text">{{ license.endDate }}</div>
        </el-col>
        <el-col :span="4">
          <div class="board-title">许可用户数</div>
          <div class="board-text">{{ license.maxUserNum }} 人</div>
        </el-col>
        <el-col :span="4">
          <div class="board-title">使用用户数</div>
          <div class="board-text">{{ license.curUserNum }} 人</div>
        </el-col>
        <el-col :span="4">
          <div class="board-title">可用用户数</div>
          <div class="board-text">{{ license.usableUserNum }} 人</div>
        </el-col>
        <el-col :span="4">
          <div class="board-title">可用天数</div>
          <div class="board-text">{{ license.usableDateNum }} 天</div>
        </el-col>
      </el-row>
    </div>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".lic"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“lic”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {getPermitInfo} from "@/api/aitcommon/license";
import axios from 'axios';

export default {
  name: "redis",
  data() {
    return {
      license: {
        startDate:"",
        endDate:"",
        maxUserNum:0,
        curUserNum:0,
        usableUserNum:0,
        usableDateNum:0,
      },
      loading: false,
      loadTime:'',
      // 定时刷新(秒)
      timeSec: 60*60,
      timeChecked: true,
      timer: {},
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        // updateSupport: 0,
        // 设置上传的请求头部
        //headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ait/common/lincense/importPermit"
      },
    }
  },
  created() {
    this.getlist();

    // 设置定时刷新
    if (this.timeChecked) {
      this.timer = window.setInterval(this.getlist, this.timeSec * 1000);
    } else {
      window.clearInterval(this.timer);
    }
  },
  methods: {
    getlist() {
      this.loading=true;
      getPermitInfo().then(res=>{
        this.license.startDate=res.data.startDate;
        this.license.endDate=res.data.endDate;
        this.license.maxUserNum=res.data.maxUserNum;
        this.license.curUserNum=res.data.curUserNum;
        this.license.usableUserNum=res.data.usableUserNum;
        this.license.usableDateNum=res.data.usableDateNum;
      }).finally(() => {
        this.loading=false;
        this.loadTime=this.parseTime(new Date());
      });
    },
    async downloadFile() {
      try {
        const response = await axios.get(process.env.VUE_APP_BASE_API+'/ait/common/lincense/downloadRequest', {
          responseType: 'blob' // 必须设置为 blob 类型，才能正确处理文件流
        });
        // const response = await getPermitFile();

        // 创建一个临时的下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;

        // 获取文件名（从响应头中提取）
        const contentDisposition = response.headers['content-disposition'];
        let fileName = 'license.req';

        if (contentDisposition) {
          const fileNameMatch = contentDisposition.match(/filename="?([^"]+)"?/);
          if (fileNameMatch.length > 1) {
            fileName = fileNameMatch[1];
          }
        }

        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        link.remove();
      } catch (error) {
        console.error('下载失败:', error);
        this.$alert('下载失败，请重试。');
      }
    },
    /** 导入按钮操作 */
    importFile() {
      this.upload.title = "许可文件导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>

<style lang="scss" scoped>
.board-hover {
  &:hover {
    box-shadow: 0 2px 12px 0 brown;
  }
}
.tip{
  float: right;
  color:gray;
  font-size: 10px;
  margin-right: 10px;
}
.board {
  .board-button{
    margin: 15px;
  }

  .board-title {
    font-size: medium;
    color: white;
    text-align: center;
    padding: 15px;
    background-color: #304156;
    border-style: dashed;
    border-color: gray;
    border-width: 1px;
    border-bottom: none;
  }

  .board-text {
    font-size: 24px;
    color: darkslategray;
    text-align: center;
    padding: 15px;
    background-color: #E8F4FF;
    margin-bottom: 12px;
    border-style: dashed;
    border-color: gray;
    border-width: 1px;
    border-top: none;

    &:hover {
      color: brown;
      text-shadow: 2px 2px 5px;
    }
  }
}
</style>